package com.kanshu.ksgb.fastread.doudou.module.personal.utils

import android.annotation.SuppressLint
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.support.v7.app.AppCompatDialog
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.common.business.pay.event.PayActionEvent
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.DynamicSimpleRetrofit
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper
import com.kanshu.ksgb.fastread.doudou.common.net.rx.BaseObserver
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import me.drakeet.support.toast.ToastCompat
import org.greenrobot.eventbus.EventBus


/**
 * Created by daniel on 18-3-1
 */
class PaymentVersion(val context: Context) {
    companion object {
        const val TYPE_READER = 1
        const val TYPE_OTHER = 0
    }

    val apiService: PersonCenterService
    var rewardsDialog: AppCompatDialog? = null
    var mMyCallBack: MyCallBack? = null
    var mType: Int = 0

    init {
        val helper = RetrofitHelper.getInstance()
        //helper.setRetrofit(DynamicSimpleRetrofit.getInstance())
        apiService = helper.createService(DynamicSimpleRetrofit::class.java, PersonCenterService::class.java)
    }

    fun setCallBack(myCallBack: MyCallBack) {
        mMyCallBack = myCallBack
    }


    fun checkIsFreeVersion() {
        apiService.isFreeVersion()
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BaseObserver<VersionConfig>() {

                    override fun onResponse(result: BaseResult<VersionConfig>, s: VersionConfig, disposable: Disposable) {
                        MMKVDefaultManager.getInstance().setIsFreeVersion(s.is_free_version)
                        try {
                            MMKVDefaultManager.getInstance().dailyCoinReward = s.give_coin.toInt()
                        } catch (e: NumberFormatException) {
                            e.printStackTrace()
                        }
                    }

                })

    }

    fun getCoinReword(preDialog: AppCompatDialog) {
        apiService.getCoinReword()
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BaseObserver<String>() {
                    override fun onResponse(tBaseResult: BaseResult<String>?, t: String?, disposable: Disposable?) {
                        Log.i("test", "xxx" + t)
                        showResultDialog()
                        EventBus.getDefault().post(PayActionEvent())
                    }

                    override fun onSubscribe(d: Disposable?) {
                        preDialog.dismiss()
                    }

                    override fun onError(code: Int, errDesc: String?) {
                        super.onError(code, errDesc)
                        ToastCompat.makeText(context, errDesc, Toast.LENGTH_SHORT).show()
                        preDialog.dismiss()
                    }
                })
    }

    fun checkDailyRewordStatus(type: Int, isRich: Boolean) {
        mType = type
        apiService.checkRewordStatus()
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BaseObserver<RewardsStatus>() {
                    override fun onResponse(tBaseResult: BaseResult<RewardsStatus>?, t: RewardsStatus?, disposable: Disposable?) {
                        Log.i("test", t.toString())
                        if (t?.is_aready_get_coin != 1) {
                            showCoinDialog()
                        } else {
                            //判断是否有金币
                            if (!isRich) mMyCallBack?.onCallBack(0)
                        }
                    }

                    override fun onError(code: Int, errDesc: String?) {
                        Log.i("test", "errorMsg:  $errDesc")
                    }
                })
    }

    fun showCoinDialog() {
        val showing: Boolean = rewardsDialog?.isShowing ?: false
        if (showing) {
            return
        }
        rewardsDialog = AppCompatDialog(context, R.style.full_screen_dialog)
        val view = View.inflate(context, R.layout.layout_coin_bg, null)
        val btnGet = view.findViewById(R.id.get_now) as Button
        val coinCountView = view.findViewById(R.id.text3) as TextView
        val tipsTv = view.findViewById(R.id.tv_tips) as TextView
        val coinCount = MMKVDefaultManager.getInstance().dailyCoinReward
        if (mType == TYPE_READER) {
            val tips = context.getString(R.string.tips_coin_reader)
            tipsTv.text = String.format(tips, coinCount)
            tipsTv.visibility = View.VISIBLE
        }
        coinCountView.text = coinCount.toString()
        btnGet.setOnClickListener {

            getCoinReword(rewardsDialog!!)
        }
        val btnClose = view.findViewById(R.id.btn_close) as ImageButton
        btnClose.setOnClickListener {
            rewardsDialog?.dismiss()
            mMyCallBack?.onCallBack(0)
        }
        rewardsDialog?.setContentView(view)
        //TODO
        if (context is AppCompatActivity) {
            if (!context.isFinishing) {
                rewardsDialog?.show()
            }
        }

    }

    @SuppressLint("SetTextI18n")
    fun showResultDialog() {
        val dialog = AppCompatDialog(context, R.style.full_screen_dialog)
        val view = View.inflate(context, R.layout.layout_coin_got, null)
        val btnClose = view.findViewById(R.id.btn_close) as ImageButton
        val textView3 = view.findViewById(R.id.text3) as TextView
        val textView7 = view.findViewById(R.id.text7) as TextView
        val count = MMKVDefaultManager.getInstance().dailyCoinReward.toString()
        val tips = context.getString(R.string.format_reward)
        val tipsTv = view.findViewById(R.id.tv_tips) as TextView
        if (mType == TYPE_READER) {
            tipsTv.visibility = View.VISIBLE
        }
        textView7.text = String.format(tips, count)
        textView3.text = count + " "
        btnClose.setOnClickListener {
            dialog.dismiss()
            mMyCallBack?.onCallBack(1)
        }
        dialog.setContentView(view)
        if (context is AppCompatActivity) {
            if (!context.isFinishing) {
                dialog.show()
            }
        }
    }
}

public interface MyCallBack {
    fun onCallBack(type: Int)
}